/**
 * 认证模块
 */
layui.define(function (exports) {
    layui.use(["layer", "element", 'setter', 'view', 'AppHelper', 'storage'], function () {
        var layer = layui.layer;
        var setter = layui.setter;
        var request = setter.request
            , tokenStorage = layui.storage
            , AppHelper = layui.AppHelper
        ;
        var $ = layui.$;


        /**
         * 对外暴露的方法
         */
        exports("auth", {})

        //ajax设置
        $.ajaxSetup({
            cache: false,
            beforeSend: function (XHR) {
                XHR.setRequestHeader("Authorization", "Bearer " + (layui.data(setter.tableName)[request.tokenName] || ''));
            }
            , statusCode: {
                200: function (res, status, xhr) {
                    if (xhr.getResponseHeader("Authorization") != null) {
                        tokenStorage.saveToken(xhr.getResponseHeader("Authorization"))
                    }
                    if (parent.layer) {
                        parent.layer.closeAll('loading');
                    }
                    if (!res.ignore && res.code != "200" && res.code != undefined) {
                        layer.msg(res.message, {icon: 0});
                    }
                    if (res.code == '5223') {
                        var topWindow = AppHelper.getTopWindow();
                        var dir = layui.setter.base.replace("layuiadmin/", layui.setter.dir);
                        topWindow.location.href = dir + "admin/login.html";
                    }
                },
                400: function (xhr) {
                    var res = xhr.responseJSON;
                    switch (res.code) {
                        case "110001":
                            layer.alert(res.message);
                            break;
                    }
                }
                , 401: function () {
                    var topWindow = AppHelper.getTopWindow();
                    var dir = layui.setter.base.replace("layuiadmin/", layui.setter.dir);
                    topWindow.location.href = dir + "admin/login.html";
                }
                , 403: function () {
                    var topWin = AppHelper.getTopWindow();
                    topWin.layui.layer.alert("您没有权限访问", {icon: 0});
                }
            }
        });

        if (typeof juicer != "undefined") {
            juicer.register('clean', function (val) {
                return val ? val : "";
            });
        }
    });
});

